<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <div>
    <BasicTable
      @register="registerTable"
      @row-contextmenu="handleContext"
      @row-db-click="rowDbClick"
    >
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-checkbox v-model:checked="hideInvalidDoc">隐藏失效文档</a-checkbox>
      </template>
      <template #firstColumn="{ record }">
        <a
          @click="
            handleForm({ cdocumentid: record.cdocumentid, cdocumentver: record.cdocumentver })
          "
        >
          {{ record.cdocumentname }}
        </a>
      </template>
    </BasicTable>
    <Loading :loading="loading" :absolute="absolute" :tip="tip" />
    <BasicModal
      :title="t('问题反馈')"
      @register="registerModal"
      @ok="handleQusSubmit"
      :minHeight="300"
      :width="600"
      :forceRender="true"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsPlmDocPLMDocInfoList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref, watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { ActionItem, BasicTable, TableCustomRecord, useTable } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import { customListData, listSet } from '/@/api/test/testData';
  import { schemasData, tabConfigData } from '/@/utils/custom';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useGo } from '/@/hooks/web/usePage';
  import { encryptRSA } from '/@/utils/encrypt/RSA';
  import { useContextMenu } from '/@/hooks/web/useContextMenu';
  import { Loading } from '/@/components/Loading';
  import { downloadByUrl } from '/@/utils/file/download';
  import { otherHttp } from '/@/utils/http/axios';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { sendQusData } from '/@/api/plm/doc/commons';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  const { createMessage, showMessage } = useMessage();
  const { ctxAdminPath } = useGlobSetting();
  const [createContextMenu] = useContextMenu();

  const { userInfo } = useUserStore();

  const go = useGo();

  const { t } = useI18n('plm.doc.pLMDocInfo');

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  let title = ref('');

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 8, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    schemas: [],
  });

  const actionColumn: BasicColumn = {
    width: 80,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('问题反馈'),
        onClick: handleQesForm.bind(this, record),
      },
    ],
  };

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('接收人'),
      field: 'receiver',
      fieldLabel: 'receiveName',
      component: 'ListSelect',
      componentProps: {
        selectType: 'userSelect',
      },
      required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('问题描述'),
      field: 'quesData',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 200,
        rows: 10,
      },
      required: true,
      colProps: { lg: 24, md: 24 },
    },
  ];

  let hideInvalidDoc = ref(false);

  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:file-outlined',
    value: router.currentRoute.value.meta.title || t('文档库'),
  };

  const props = defineProps({
    treeCode: String,
    treeName: String,
  });

  watch(
    () => props.treeCode,
    async () => {
      reload();
    },
  );

  watch(
    () => hideInvalidDoc.value,
    async () => {
      reload();
    },
  );

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerModal, { openModal, setModalProps, closeModal }] = useModal();
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });
  onMounted(async () => {
    setTimeout(async () => {
      const res = await listSet({ viewCode: 'doc_docManager_list_01' });
      title.value = res.layVoucherView.name;
      layVoucherView.value = res.layVoucherView;
      searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);
      tableColumns.value = layVoucherView.value.flistTabCols; //表格表头
      butData.value = layVoucherView.value.headBtns; //表格右上角按钮

      actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

      listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
      setProps({
        ...listTabConfig.value,
        api: customListData,
        beforeFetch: (params) => {
          params.url = listTabConfig.value.api;
          params.queryConfigKey = layVoucherView.value?.listQuery.code;
          params.viewConfigKey = layVoucherView.value?.code;
          params.cmkindid = props.treeCode;
          if (hideInvalidDoc.value) {
            params.hideInvalidDoc = '9';
          }
          return params;
        },
        rowClassName: (record: TableCustomRecord<any>, index: number) => {
          if (record.cdlock === '9') {
            return 'doc-table-bg-red';
          }
          if (record.cdlock === '6') {
            return 'doc-table-bg-blue';
          }
          if (record.cdlock === '3') {
            return 'doc-table-bg-green';
          }
          return '';
        },
      });
      if (!listTabConfig.value.immediate) {
        reload();
      }
    }, 500);
  });

  const [registerTable, { reload, setProps, getForm }] = useTable({
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    actionColumn: actionColumn,
  });

  const picTypes = ['png', 'jpg', 'jpeg', 'gif', 'txt', 'mp4'];

  let loading = ref(false);
  let absolute = ref(false);
  let tip = ref('加载中...');
  let quesData = ref('');
  let currentDocCode = ref('');
  let currentDocVer = ref('');
  let currentDocName = ref('');

  async function handlePreview(record: Recordable, bviewPdf: String) {
    const url =
      ctxAdminPath +
      '/plm/file/previewNew?docCode=' +
      record.cdocumentid +
      '&docVer=' +
      record.cdocumentver +
      '&docType=' +
      record.cdformat;
    let layerWidth = $(window).width();
    if (layerWidth < 800) {
      layerWidth -= 15 * 2;
    } else {
      layerWidth -= 100 * 2;
    }
    let layerHeight = $(window).height();
    if (layerHeight < 500) {
      layerHeight -= 15 * 2;
    } else {
      layerHeight -= 25 * 2;
    }
    if (picTypes.includes(record.cdformat)) {
      window.layer.open({
        type: 2,
        maxmin: true,
        shadeClose: false, // 点击背景关闭
        title: false,
        area: [layerWidth + 'px', layerHeight + 'px'],
        method: 'get',
        content: url,
      });
      return;
    }
    const params = {
      docCode: record.cdocumentid,
      docVer: record.cdocumentver,
      docType: bviewPdf === '1' ? 'pdf' : record.cdformat,
      bviewPdf: bviewPdf,
    };
    go({
      path: '/plm/doc/pLMDocInfo/fileView',
      query: {
        params: encryptRSA(JSON.stringify(params)),
      },
    });
  }

  async function handleContext(record: any, row: Number, e: MouseEvent) {
    const docInfo = {
      docCode: record.cdocumentid,
      docVer: record.cdocumentver,
      docType: record.cdformat,
    };
    e.preventDefault();
    const privilige = await otherHttp.get({
      url: `/rest/preview/getDocPrivilige/${docInfo.docCode}/${docInfo.docVer}/${userInfo?.userCode}`,
    });
    const { result, downoriginalfile, downpdffile, bviewResourceFile, bviewPdfFile } = privilige;
    console.log(privilige);
    if (result !== 'success') {
      return;
    }
    console.log(privilige);
    createContextMenu({
      event: e,
      items: [
        {
          label: '浏览',
          handler: () => {
            handlePreview(record, '0');
          },
          disabled: !bviewResourceFile,
        },
        {
          label: '浏览PDF',
          handler: () => {
            handlePreview(record, '1');
          },
          disabled: !bviewPdfFile,
        },
        {
          label: '下载',
          handler: () => {
            downloadByUrl({
              url: `/rest/preview/view/${record.cdocumentid}/${record.cdocumentver}/download`,
            });
          },
          disabled: !downoriginalfile,
        },
        {
          label: '下载PDF',
          handler: () => {
            downloadByUrl({
              url: `/rest/preview/viewPdf/${record.cdocumentid}/${record.cdocumentver}/download`,
            });
          },
          disabled: !downpdffile,
        },
      ],
    });
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  function handleSuccess() {
    reload();
  }

  async function rowDbClick(record) {
    loading.value = true;
    const privilige = await otherHttp.get({
      url: `/rest/preview/getDocPrivilige/${record.cdocumentid}/${record.cdocumentver}/${userInfo?.userCode}`,
    });
    loading.value = false;
    const { bviewResourceFile, bviewPdfFile } = privilige;
    if (picTypes.includes(record.cdformat)) {
      if (!bviewResourceFile) {
        createMessage.error('无预览权限！');
        return;
      } else {
        handlePreview(record, '0');
        return;
      }
    }
    if (!picTypes.includes(record.cdformat)) {
      if (!bviewPdfFile) {
        createMessage.error('无预览权限！');
        return;
      } else {
        handlePreview(record, '1');
        return;
      }
    }
  }

  function handleQesForm(record) {
    quesData.value = '';
    currentDocCode.value = record.cdocumentid;
    currentDocVer.value = record.cdocumentver;
    currentDocName.value = record.cdocumentname;
    openModal();
    setFieldsValue({
      receiver: record.creator?.cpersonid,
      receiveName: record.creator?.cpersonname,
    });
  }

  async function handleQusSubmit() {
    try {
      const data = await validate();
      console.log(data);
      setModalProps({ confirmLoading: true });
      const params = {};
      const reqData = {
        sender: userInfo?.userCode,
        receiver: data.receiver,
        subject: '文档错误',
        content: `文档如下：
  文档名为：（${currentDocName.value}）编码：（${currentDocCode.value}）版本：（${currentDocVer.value}）的文档。

  反馈内容如下：
      ${data.quesData}
                 `,
      };
      console.log(params);
      const { message } = await sendQusData(params, reqData);
      showMessage(message);
      setTimeout(closeModal);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style>
  .doc-table-bg-red {
    color: red !important;
  }
  .doc-table-bg-blue {
    color: blue !important;
  }
  .doc-table-bg-green {
    color: green !important;
  }
</style>
